package com.lz.headers;

import com.lz.RabbitMQConnector;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;

import java.util.HashMap;
import java.util.Map;

/**
 * 生产者
 */
public class ProducerHeaders {
    public static void main(String[] args) throws Exception {
        String exchangeName = "lz_exchange_headers";
        String queueName1 = "lz_queue_headers_1";
        String queueName2 = "lz_queue_headers_2";


        Channel channel = RabbitMQConnector.createConnectionAndChannel();

        /**
         * 创建交换机
         */
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.HEADERS, true, false, null);


        /**
         * 创建队列
         */
        channel.queueDeclare(queueName1, true, false, false, null);
        channel.queueDeclare(queueName2, true, false, false, null);

        // 创建一个HashMap实例，用于存储绑定队列时的额外属性
        Map<String, Object> allMap = new HashMap<>();
        // 设置匹配规则，"all"表示所有条件必须都满足
        allMap.put("x-match", "all");
        allMap.put("name","lizheng");
        allMap.put("sex","男");

        // 绑定队列到交换机，使用空的路由键和之前设置的额外属性
        channel.queueBind(queueName1, exchangeName, "", allMap);


        Map<String, Object> anyMap = new HashMap<>();
        anyMap.put("x-match", "any");
        anyMap.put("name","lizheng");
        anyMap.put("age","24");

        channel.queueBind(queueName2, exchangeName, "", anyMap);

        // 创建一个HashMap实例，用于存储消息的属性
        Map<String, Object> hashMap1 = new HashMap<>();
        hashMap1.put("name","lizheng");
        hashMap1.put("sex","男");
        // 使用hashMap1中的数据构建AMQP.BasicProperties对象
        AMQP.BasicProperties.Builder Properties1 = new AMQP.BasicProperties().builder().headers(hashMap1);


        Map<String, Object> hashMap2 = new HashMap<>();
        hashMap2.put("sex","女");
        hashMap2.put("age","24");
        AMQP.BasicProperties.Builder Properties2 = new AMQP.BasicProperties().builder().headers(hashMap2);


        /**
         * 发送消息
         * 1.发送到哪个交换机
         * 2.路由键 routingKey
         * 3.其他参数信息
         * 4.消息主体
         */
        channel.basicPublish(exchangeName, "", Properties1.build(), "all message".getBytes());
        channel.basicPublish(exchangeName, "", Properties2.build(), "any message".getBytes());
        System.out.println("发送消息成功");
        RabbitMQConnector.closeResources();
    }
}
